package com.family.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.family.domain.Desk;
import com.family.domain.Food;
import com.family.inter.IDesk;
import com.family.inter.IFood;
import com.family.tools.DeleteFileUtil;
import com.family.tools.FileToZip;
import com.family.tools.QRUtil;
import com.family.tools.SpringToos;
import com.google.common.io.Files;

@Controller
public class UploadAction {

    @Resource
    IDesk idesk;

    @Resource
    IFood ifood;

    public static Properties prop =  new  Properties();
    static {
        try {
//			File cfgFile = ResourceUtils.getFile("classpath:app.properties");
//			InputStream in = new FileInputStream(cfgFile);
            InputStream in = UploadAction.class.getClassLoader().getResourceAsStream("app.properties");
            prop.load(in);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/upload")
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;

        File imgdir = new File(prop.getProperty("imgpath"));
        if(imgdir.exists()==false)
        {
            imgdir.mkdir();
        }

        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String filename = prop.getProperty("imgpath")+file.getOriginalFilename();
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filename)));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "保存失败";

                }
            }

        }
        String js = "<script type=\"text/javascript\">alert();</script>";
        return js;

    }


    @RequestMapping("/exelupload")
    public String upExel(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;


        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String fname = file.getOriginalFilename();
            if(fname.endsWith("xls")==false)
            {
                return "err";
            }
            if (!file.isEmpty()) {
                try {

                    Workbook rwb = Workbook.getWorkbook(file.getInputStream());
                    Sheet rs = rwb.getSheet(0);

                    int rows = rs.getRows();

                    String mark = rs.getCell(0, 0).getContents().trim();
                    if(mark.equals("菜品名")==false)
                    {
                        return "err";
                    }

                    for(int r=0;r<rows;r++)
                    {

                        Food food = new Food();

                        UUID uuid = UUID.randomUUID();
                        food.setId(uuid.toString());


                        String name = rs.getCell(0, r).getContents().trim();
                        if(name.equals("菜品名 "))
                        {
                            continue;
                        }
                        food.setFoodname(name);

                        String price = rs.getCell(1, r).getContents().trim();
                        food.setPrice(price);

                        String type = rs.getCell(2, r).getContents().trim();
                        food.setIsfood(type);

                        String image = rs.getCell(3, r).getContents().trim();
                        food.setImage(image);

                        food.setScore("0");

                        ifood.addFood(food);

                    }


                } catch (Exception e) {
                    return "err";

                }
            }

        }
        return "message";

    }


    @RequestMapping(value="/qr", method=RequestMethod.GET)
    public void getDownload(HttpServletRequest request, HttpServletResponse response) {

        List<Desk> all = idesk.getAllDesk();
        String DIR = UploadAction.prop.getProperty("QRimgdir");
        File qrdir = new File(DIR);
        if(qrdir.exists())
        {
            qrdir.delete();
        }else
        {
            qrdir.mkdir();
        }

        for(Desk desk :all)
        {
            String path = DIR+desk.getIdnum()+"号_"+desk.getDname()+".gif";
            String url ="http://"+SpringToos.getLocalIp()+":"+UploadAction.prop.getProperty("port")+"/p_main?deskid="+desk.getId();
            QRUtil.creatQrImag(url, path);
        }


        boolean flag = FileToZip.fileToZip(DIR,UploadAction.prop.getProperty("zipname"));


        // Get your file stream from wherever.
        String fullPath = UploadAction.prop.getProperty("zipname");
        File downloadFile = new File(fullPath);

        ServletContext context = request.getServletContext();

        // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
            System.out.println("context getMimeType is null");
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",
                downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        // Copy the stream to the response's output stream.
        InputStream myStream=null;
        try {
            myStream = new FileInputStream(fullPath);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(myStream!=null)
            {
                try {
                    myStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        DeleteFileUtil.deleteDirectory(UploadAction.prop.getProperty("QRimgdir"));

        DeleteFileUtil.deleteFile(fullPath);


    }


    @RequestMapping(value="/save_qrImag", method=RequestMethod.GET)
    public void save_qrImag(String id, HttpServletRequest request, HttpServletResponse response) {

        String DIR = "c:/QRImage/";
        File qrdir = new File(DIR);
        if(qrdir.exists())
        {
            qrdir.delete();
        }else
        {
            qrdir.mkdir();
        }

        Desk desk = idesk.getDeskById(id);

        String path = DIR+desk.getIdnum()+"号_"+desk.getDname()+".gif";
        String url ="http://"+SpringToos.getLocalIp()+":"+UploadAction.prop.getProperty("port")+"/p_main?deskid="+desk.getId();
        QRUtil.creatQrImag(url, path);



        // Get your file stream from wherever.
        File downloadFile = new File(path);

        ServletContext context = request.getServletContext();

        // get MIME type of the file
        String mimeType = context.getMimeType(path);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
            System.out.println("context getMimeType is null");
        }
        System.out.println("MIME type: " + mimeType);

        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        String uname = null;
        try {
            uname = URLEncoder.encode(downloadFile.getName(), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",
                uname);
        response.setHeader(headerKey, headerValue);

        // Copy the stream to the response's output stream.
        InputStream myStream=null;
        try {
            myStream = new FileInputStream(path);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(myStream!=null)
            {
                try {
                    myStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        DeleteFileUtil.deleteDirectory("c:/QRImage");

    }

}
